<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.status">
        <!-- <CommentDropdown v-model="postForm.comment_disabled" /> -->
        <!-- <PlatformDropdown v-model="postForm.platforms" /> -->
        <!-- <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        <el-button
          v-loading="loading"
          style="margin-left: 10px"
          type="success"
          @click="submitForm"
        >
          {{ this.isEdit ? "修改" : "发表" }}
        </el-button>
        <!-- <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button> -->
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <!-- <Warning /> -->

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px" prop="title">
              <MDinput
                v-model="postForm.title"
                :maxlength="100"
                name="name"
                required
              >
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label-width="60px"
                    label="作者:"
                    class="postInfo-container-item"
                  >
                    <el-select
                      v-model="postForm.appUserId"
                      filterable
                      default-first-option
                      placeholder="选择新闻作者"
                    >
                      <el-option
                        v-for="item in userListOptions"
                        :key="item.id"
                        :label="item.nickName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- 新闻分类 -->
                <el-col :span="8">
                  <el-form-item
                    label-width="80px"
                    label="新闻分类:"
                    class="postInfo-container-item"
                  >
                    <el-select
                      v-model="postForm.newsCategoryId"
                      filterable
                      default-first-option
                      placeholder="选择新闻分类"
                    >
                      <el-option
                        v-for="item in newsCategoryListOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
            style="margin-bottom: 40px"
            label-width="60px"
            label="简介:"
          >
            <el-input
              v-model="postForm.describe"
              :rows="1"
              type="textarea"
              class="article-textarea"
              autosize
              placeholder="Please enter the describe"
            />
            <span
              v-show="contentShortLength"
              class="word-counter"
            >{{ contentShortLength }}words</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="titlePic"
            label-width="60px"
            label="封面："
            style="margin-bottom: 30px"
          >
            <el-image
              v-if="isEdit && imgVisiable"
              style="width:180px;height:180px;float:left;margin-right:20px;"
              :src="baseImgURL + postForm.titlePic"
            />
            <Upload
              v-model="postForm.titlePic"
              style="float:left;"
              action-u-r-l="NewsTitlePic"
              @returnUrl="handleReturnUrl"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="content" label="正文" style="margin-bottom: 30px">
            <Tinymce ref="editor" v-model="postForm.content" :height="600" />
          </el-form-item>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/Upload'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
// import { fetchArticle } from "@/api/article";

import { fetchUserList } from '@/api/user'
import { getAll } from '@/api/newsCategory'
import { createNews, getInShowSingle, updateNews } from '@/api/news'

import {baseNewsTitlePicURL} from '@/utils/constTool'

const defaultForm = {
  // status: 'draft',
  // title: '', // 文章题目
  // content: '', // 文章内容
  // content_short: '', // 文章摘要
  // source_uri: '', // 文章外链
  // image_uri: '', // 文章图片
  // display_time: undefined, // 前台展示时间
  // id: undefined,
  // platforms: ['a-platform'],
  // comment_disabled: false,
  // importance: 0

  appUserId: undefined,
  appUserName: '',
  content: '',
  describe: '',
  id: undefined,
  newsCategoryId: undefined,
  newsCategoryName: '',
  newsStatusId: undefined,
  newsStausName: '',
  title: '',
  titlePic: 'Default.jpg',
  weight: 0
}

export default {
  name: 'ArticleDetail',
  components: {
    Tinymce,
    MDinput,
    Upload,
    Sticky
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      imgVisiable: true,
      baseImgURL: baseNewsTitlePicURL,

      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      newsCategoryListOptions: [],
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.describe.length
      // return 1;
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return +new Date(this.postForm.display_time)
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    // console.log(this.isEdit);
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      console.log(id)
      // 如果是编辑状态而且id为空:即用户直接想跳转到Edit页面,而没有带参数
      if (id === undefined || id === '') {
        this.$router.push({
          name: 'NewsInShowList'
        })
        return
      }
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)

    this.getRemoteUserList()
    this.getRemoteNewsCategoryList()
  },
  methods: {
    fetchData(id) {
      getInShowSingle(id)
        .then((response) => {
          this.postForm = response.data
          console.log(this.postForm)
          // just for test
          // this.postForm.title += `   Article Id:${this.postForm.id}`;
          // this.postForm.content_short += `   Article Id:${this.postForm.id}`;

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = 'Edit Article'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 检查当前组件是Edit还是Create
          if (!this.isEdit) {
            createNews(this.postForm, this.postForm.appUserId)
              .then(() => {
                this.resetPostForm()
                this.$notify({
                  title: '成功',
                  message: '发布文章成功',
                  type: 'success',
                  duration: 2000
                })
              })
          } else {
            updateNews(this.postForm).then(() => {
              this.$notify({
                title: '成功',
                message: '修改文章成功',
                type: 'success',
                duration: 2000
              })
            })
          }

          // this.postForm.status = "published";
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (
        // this.postForm.content.length === 0 ||
        // this.postForm.title.length === 0
        1
      ) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList() {
      fetchUserList().then((response) => {
        // console.log(response);
        if (!response.data) return
        // this.userListOptions = response.data.items.map((v) => v.name);
        this.userListOptions = response.data
      })
    },
    getRemoteNewsCategoryList() {
      getAll().then((response) => {
        // console.log(response);
        if (!response.data) return
        // this.userListOptions = response.data.items.map((v) => v.name);
        this.newsCategoryListOptions = response.data
      })
    },
    handleReturnUrl(data) {
      this.postForm.titlePic = data
      this.imgVisiable = false
    },
    resetPostForm() {
      this.postForm.appUserId = undefined
      this.postForm.appUserName = ''
      this.postForm.content = ''
      this.postForm.describe = ''
      this.postForm.id = undefined
      this.postForm.newsCategoryId = undefined
      this.postForm.newsCategoryName = ''
      this.postForm.newsStatusId = undefined
      this.postForm.newsStausName = ''
      this.postForm.title = ''
      this.postForm.titlePic = 'Default.jpg'
      this.postForm.weight = 0
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
